import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

# 须知：提前手动走一遍流程，获取cookie和验证码


# 记录成功日志 包括第i次是否成功 成功次数等
import logging
# 删除之前的日志文件
import os
if os.path.exists('userbuy_test.log'):
    os.remove('userbuy_test.log')
logging.basicConfig(filename='userbuy_test.log',level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

i = 1
success_count = 0
erro_count = 0

start_time = 0
end_time = 0

def test_userbuy():

    global i
    global success_count
    global erro_count
    global start_time
    global end_time

    # 初始化 WebDriver
    driver = webdriver.Chrome()
    vars = {}
    
    try:
        # 测试步骤开始
        driver.get("http://192.168.49.2:32677/")  # 更改成运行的那个trainticket页面
        # driver.set_window_size(1708, 1020)
        driver.maximize_window()  # 最大化窗口
        # 缩放页面 90%
        driver.execute_script("document.body.style.zoom='90%'")

        driver.find_element(By.CSS_SELECTOR, ".am-icon-sign-out").click()
        # 等待弹窗alert加载
        WebDriverWait(driver, 10).until(
            expected_conditions.alert_is_present()
        )
        # 接受弹窗
        driver.switch_to.alert.accept()


        # try:
        #     driver.find_element(By.CSS_SELECTOR, ".form-horizontal").click()
        # except Exception as e:
        #     pass
        # 等待登录页面加载

        WebDriverWait(driver, 10).until( 
            expected_conditions.presence_of_element_located((By.ID, "flow_preserve_login_verification_code"))
        )
        
        # 注意：验证码固定
        captcha = "E24G"
        # 先清空输入框
        driver.find_element(By.ID, "flow_preserve_login_verification_code").clear()
        # 输入验证码
        driver.find_element(By.ID, "flow_preserve_login_verification_code").send_keys(captcha)
        # 设置cookie
        driver.add_cookie({"name": "YsbCaptcha", "value": "D1FB4578F3E94303B641B945A2287C97"})  # 替换为实际的 session ID
        driver.find_element(By.ID, "client_login_button").click()
        # 等待页面加载 //*[@id="flow_preserve_login_msg"] 显示为 login success
        WebDriverWait(driver, 10).until(
            expected_conditions.visibility_of_element_located((By.ID, "flow_preserve_login_msg"))
        )        
        driver.find_element(By.CSS_SELECTOR, ".tpl-left-nav-item:nth-child(1) span").click()
        driver.find_element(By.ID, "travel_searching_button").click()
        
        # 等待//*[@id="tickets_booking_list_table"]/tbody/tr/td[11]/button 可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, ".ticket_booking_button"))
        )

        

        
        
        
        driver.find_element(By.CSS_SELECTOR, ".ticket_booking_button").click()
        # 等待//*[@id="need-food-or-not"] 可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.ID, "need-food-or-not"))
        )
        driver.find_element(By.ID, "need-food-or-not").click()
        driver.find_element(By.ID, "preserve_food_type").click()
        # 等待下拉框加载
        WebDriverWait(driver, 10).until(
            expected_conditions.presence_of_element_located((By.ID, "preserve_food_type"))
        )

        # 选择下拉框选项
        dropdown = driver.find_element(By.ID, "preserve_food_type")
        # 等待下拉框选项可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.ID, "train-food-option"))
        )
        
        dropdown.find_element(By.ID, "train-food-option").click()
        
        driver.find_element(By.ID, "train-food-type-list").click()
        dropdown = driver.find_element(By.ID, "train-food-type-list")
        # 等待下拉框选项可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.XPATH, "//option[. = 'Soup:$3.7']"))
        )
        dropdown.find_element(By.XPATH, "//option[. = 'Soup:$3.7']").click()
        
        driver.find_element(By.NAME, "booking_contacts").click()
        driver.find_element(By.ID, "ticket_select_contacts_confirm_btn").click()
        
        # 等待按钮可点击 //*[@id="my-prompt"]/div/div[19]/span[2]
    
        WebDriverWait(driver, 20).until(
            expected_conditions.element_to_be_clickable((By.XPATH, "//*[@id='my-prompt']/div/div[19]/span[2]"))
        )

        driver.find_element(By.XPATH, "//*[@id='my-prompt']/div/div[19]/span[2]").click()
        # 等待提示框出现
        WebDriverWait(driver, 100).until(
            expected_conditions.alert_is_present()
        )
        

        # 验证提示框
        alert_text = driver.switch_to.alert.text
        print(f"Alert text: {alert_text}")
        assert alert_text == "Success.---please go to order list to pay for it!"
        driver.switch_to.alert.accept()
        
        driver.find_element(By.LINK_TEXT, "Order List").click()
        # 等待页面稳定
        time.sleep(5) 
        # 等待订单列表加载
        WebDriverWait(driver, 10).until(
            expected_conditions.presence_of_element_located((By.XPATH, "//*[@id='orderListApp']/div/div[2]/table/tbody/tr[1]"))
        )

        # 等待页面稳定

        # 找到并点击 //*[@id="orderListApp"]/div/div[2]/table/tbody/tr[最后一个]/td[8]/button
        
        # last_row = driver.find_elements(By.CSS_SELECTOR, "#orderListApp > div > div.am-table > table > tbody > tr")[-1]
        last_row = driver.find_elements(By.XPATH, "//*[@id='orderListApp']/div/div[2]/table/tbody/tr")
        print(f"Total rows found: {len(last_row)}")

        # 滚动页面到底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(1)  # 等待滚动完成

        last_row = driver.find_element(By.XPATH, "//*[@id='orderListApp']/div/div[2]/table/tbody/tr[last()]")



        # 等待最后一行的按钮可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.XPATH, ".//td[8]/button"))
        )
        last_button = last_row.find_element(By.XPATH, ".//td[8]/button")
        last_button.click()

        # 等待支付按钮可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.ID, "pay_for_preserve"))
        )

        driver.find_element(By.ID, "pay_for_preserve").click()

        # 等待 弹窗并确认
        WebDriverWait(driver, 100).until(
            expected_conditions.alert_is_present()
        )
        driver.switch_to.alert.accept()
        
        driver.find_element(By.LINK_TEXT, "Execute Flow").click()


        # 更多元素操作
        element = driver.find_element(By.CSS_SELECTOR, "li:nth-child(1) > .active > span")
        actions = ActionChains(driver)
        actions.move_to_element(element).click_and_hold().perform()
        
        element = driver.find_element(By.CSS_SELECTOR, "li:nth-child(1) > .active > span")
        actions = ActionChains(driver)
        actions.move_to_element(element).perform()
        
        element = driver.find_element(By.CSS_SELECTOR, "li:nth-child(1) > .active > span")
        actions = ActionChains(driver)
        actions.move_to_element(element).release().perform()
        
        driver.find_element(By.CSS_SELECTOR, "li:nth-child(1) > .active > span").click()
        # 等待预定收集按钮可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.ID, "reserve_collect_button"))
        )
        driver.find_element(By.ID, "reserve_collect_button").click()
        # 等待弹窗并确认
        WebDriverWait(driver, 10).until(
            expected_conditions.alert_is_present()
        )
        driver.switch_to.alert.accept()
        driver.find_element(By.CSS_SELECTOR, "a:nth-child(2) > span").click()
        # 等待执行订单按钮可点击
        WebDriverWait(driver, 10).until(
            expected_conditions.element_to_be_clickable((By.ID, "enter_reserve_execute_order_button"))
        )
        driver.find_element(By.ID, "enter_reserve_execute_order_button").click()
        driver.find_element(By.CSS_SELECTOR, "body").click()

        # 等待弹窗并确认
        WebDriverWait(driver, 10).until(
            expected_conditions.alert_is_present()
        )
        driver.switch_to.alert.accept()

        # 退出登陆 点击//*[@id="logout_button"]
        driver.find_element(By.ID, "logout_button").click()
        # 等待弹窗并确认
        WebDriverWait(driver, 10).until(
            expected_conditions.alert_is_present()
        )
        driver.switch_to.alert.accept()

        print(f"第{i}测试执行成功")
        success_count += 1
        logging.info(f"第{i}测试执行成功 共有{success_count}/{i}次成功")
    
    except Exception as e:
        # print(f"测试执行过程中发生错误: {e}")
        erro_count += 1
        print(f"测试{i}次过程中发生错误: {e}")
        logging.error(f"测试{i}次过程中发生错误 共有{erro_count}/{i}次错误")
    finally:
        # 确保浏览器关闭

        i = i+1
        driver.quit()
        print(f"第{i-1}测试执行结束")
        # 记录结束时间
        end_time = time.time()
        logging.info(f"第{i-1}测试执行结束，结束时间: {end_time}")


# 判定是否超过两个小时
def is_time_exceeded(start_time, duration=7200):
    current_time = time.time()
    return (current_time - start_time) > duration
 



# 直接执行测试函数
if __name__ == "__main__":
    # 定时执行两个小时
    now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    start_time = time.time()
    print(f"开始时间: {start_time}")
    logging.info(f"开始时间: {now_time}，时间戳: {start_time}")

    print(f"开始测试 userbuy at {now_time}")


    # 设置日志记录
    logging.info("开始测试 userbuy")
    # test_userbuy()
    # while(True):
    #     test_userbuy()
    #     time.sleep(10)
    while (not is_time_exceeded(start_time)):
        test_userbuy()
        time.sleep(10)

    print(f"测试结束，共执行{i-1}次，成功{success_count}次，失败{erro_count}次")
    print(f"开始时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))}")
    logging.info(f"结束时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))}，时间戳: {end_time}")


